package com.jxd.dianping.common;

import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@ControllerAdvice // 所有执行的controller都会被这个切面包含
public class GlobalExceptionHandler {
    // 定义切面的处理规则 拦截抛出的异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public CommonRes doError(HttpServletRequest request, HttpServletResponse response, Exception e) {
        // 如果是业务异常则返回
        if (e instanceof BusinessException) {
            return CommonRes.create(((BusinessException) e).getCommonError(), "fail");
            // 访问路径异常
        } else if (e instanceof NoHandlerFoundException) {
            CommonError commonError = new CommonError(EmBusinessError.NO_HANDLER_FOUND);
            return CommonRes.create(commonError, "fail");
            // 参数绑定异常
        } else if (e instanceof ServletRequestBindingException) {
            CommonError commonError = new CommonError(EmBusinessError.PARAMETER_BINDING_ERROR);
            return CommonRes.create(commonError, "fail");
        } else { // 否则为未知异常
            CommonError commonError = new CommonError(EmBusinessError.UNKNOWN_ERROR);
            return CommonRes.create(commonError, "fail");
        }
    }
}
